package com.webull.information.center.dao;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.webull.information.client.model.NewsLabel;
import com.webull.information.client.model.parm.NewsLabelParam;

/**
 * 新闻Dao
 *
 * @author shimingjun
 * @version 1.0
 * @date 2016年6月2日 下午5:08:52
 * @since JDK 1.8
 */
/*
 * 暂不启用的代码，使用前需更新逻辑和测试
 */
@Deprecated
@Repository
public class InfoNewsLabelDao {
	private static final RowMapper<NewsLabel> newsLableRM = BeanPropertyRowMapper.newInstance(NewsLabel.class);
	protected final Logger logger = LogManager.getLogger(getClass());
	private @Autowired JdbcTemplate jdbcTemplate;
	private @Autowired NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public int add(NewsLabel label) {
		logger.trace("sql={}, label={}", Sql.ADD, ToStringBuilder.reflectionToString(label));
		KeyHolder keyHolder = new GeneratedKeyHolder();
		namedParameterJdbcTemplate.update(Sql.ADD, JdbcHelper.getSqlParameterSource(label), keyHolder);
		int id = keyHolder.getKey().intValue();
		label.setId(id);
		return id;
	}

	public Integer del(Integer id) {
		logger.trace("sql={}, id={}", Sql.DEL, id);
		return jdbcTemplate.update(Sql.DEL, id);
	}

	public List<NewsLabel> searchByIds(Integer[] ids) {
		logger.trace("sql={}, id={}", Sql.SEARCHBYIDS, ArrayUtils.toString(ids));
		Map<String, Object> paraMap = new HashMap<>();
		paraMap.put("ids", Arrays.asList(ids));
		return namedParameterJdbcTemplate.query(Sql.SEARCHBYIDS, paraMap, newsLableRM);
		// return jdbcTemplate.query(Sql.SEARCHBYID, paraMap, newsLableRM);
	}

	public Integer update(NewsLabel label) {
		logger.trace("sql={}, label={}", Sql.ADD, ToStringBuilder.reflectionToString(label));
		return namedParameterJdbcTemplate.update(Sql.UPDATE, JdbcHelper.getSqlParameterSource(label));
	}

	public List<NewsLabel> paging(NewsLabelParam param) {
		String sql = Sql.PAGING;
		if (StringUtils.isNotBlank(param.getName())) {
			sql += " and name=:name";
		}
		if (StringUtils.isNotBlank(param.getLanguage())) {
			sql = sql + " and language=:language";
		}
		if (param.getRegionIds() != null && param.getRegionIds().length > 0) {
			sql += " and region_id in (" + new Function<Integer[], String>() {
				@Override
				public String apply(Integer[] t) {
					String b = "";
					for (int i = 0; i < t.length; i++) {
						b += t[i] + ",";
					}
					return StringUtils.substringBeforeLast(b, ",");
				}
			}.apply(param.getRegionIds()) + ") ";

		}
		if (param.getIds() != null && param.getIds().length > 0) {
			sql += " and id in (" + new Function<Integer[], String>() {
				@Override
				public String apply(Integer[] t) {
					String b = "";
					for (int i = 0; i < t.length; i++) {
						b += t[i] + ",";
					}
					return StringUtils.substringBeforeLast(b, ",");
				}
			}.apply(param.getIds()) + ") ";

		}
		// 其他排序在前，避免sql报错
		if (param.getIsHot() != null && param.getIsHot()) {
			sql += " and is_hot = 1";
			sql += " order by sorting is null,sorting desc ";
		}
		if (param.getPageIndex() != null && param.getPageSize() != null) {
			sql += " limit :start, :endRow";
		}
		logger.trace("sql={}, param={}", sql, ToStringBuilder.reflectionToString(param));
		return namedParameterJdbcTemplate.query(sql, JdbcHelper.getSqlParameterSource(param), newsLableRM);
	}

	public int count(NewsLabelParam param) {
		String sql = Sql.COUNT;
		if (StringUtils.isNotBlank(param.getName())) {
			sql = sql + " and name=:name";
		}
		if (StringUtils.isNotBlank(param.getLanguage())) {
			sql = sql + " and language=:language";
		}
		if (param.getRegionIds() != null && param.getRegionIds().length > 0) {
			sql += " and region_id in (" + new Function<Integer[], String>() {
				@Override
				public String apply(Integer[] t) {
					String b = "";
					for (int i = 0; i < t.length; i++) {
						b += t[i] + ",";
					}
					return StringUtils.substringBeforeLast(b, ",");
				}
			}.apply(param.getRegionIds()) + ") ";

		}
		logger.trace("sql={}, param={}", sql, ToStringBuilder.reflectionToString(param));
		return namedParameterJdbcTemplate.queryForObject(sql, JdbcHelper.getSqlParameterSource(param), Integer.class);
	}

	private class Sql {
		public static final String ADD = "insert into wli_news_label (name, `describe`, language, is_hot,sorting,region_id) values (:name, :describe,:language,:isHot,:sorting,:regionId  )";
		public static final String DEL = "update wli_news_label set del=1 where id=?";
		public static final String UPDATE = "update wli_news_label set name=:name, `describe`=:describe,is_hot=:isHot,sorting=:sorting,region_id=:regionId, language=:language where id=:id";
		public static final String PAGING = "select * from wli_news_label where del=0";
		public static final String SEARCHBYIDS = "select * from wli_news_label where del=0 and id in (:ids)";
		public static final String COUNT = "select count(id) from wli_news_label where del=0";
	}
}
